//
//  HMComposeViewController.swift
//  WeiBo
//
//  Created by Feng on 2017/6/12.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {

    //MARK: --懒加载控件 title视图
    private lazy var titleLabel: UILabel =
    {
        let label = UILabel(fontSize: 17, textColor: UIColor.lightGray)
        
        if let name = HMUserAccountViewModel.sharedUserAccount.userAccount?.name
        {
            let content: String = "发微博\n\(name)"
            //将字符串转成富文本
            let attributedStr = NSMutableAttributedString(string: content)
            //获取名字的范围
            let range = (content as NSString).range(of: name)
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.orange], range: range)
            label.attributedText = attributedStr
        }
        else
        {
            label.text = "发微博"
        }
        
        label.textAlignment = .center
        label.numberOfLines = 0
        //一定要放在最后
        label.sizeToFit()
        
        return label
    }()
    
    //发送按钮
    fileprivate lazy var sendButton: UIButton =
    {
        let button = UIButton(title: "发送", titleColor: UIColor.white, fontSize: 15, image: nil, backgroundImage: UIImage(named: "common_button_orange"))
        
        button.setTitleColor(UIColor.lightGray, for: .disabled)
        button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        button.size = CGSize(width: 60, height: 35)
        
        button.addTarget(self, action: #selector(sendButtonAction), for: .touchUpInside)
        
        return button
    }()
    
    //textView 视图
    fileprivate lazy var composeTextView: HMComposeTextView =
    {
        let textView = HMComposeTextView()
        
        //  不显示纠错提示
        //        textView.autocorrectionType = .no

        //设置代理
        textView.delegate = self
        textView.font = UIFont.systemFont(ofSize: 15)
        textView.placeHolder = "爱马仕的拉动垃圾啊加类名vsiogosnv爱马仕的拉动垃圾啊加类名vsiogosnv爱马仕的拉动垃圾啊加类名vsiogosnv爱马仕的拉动垃圾啊加类名vsiogosnv爱马仕的拉动垃圾啊加类名vsiogosnv"
        
        return textView
    }()
    
    //toolBarView 底部工具栏
    fileprivate lazy var toolBarStackView: HMToolBarStackView =
    {
        let stackView = HMToolBarStackView()
        
        return stackView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setupUI()
        setupNavUI()
    }
    
    //设置pictureView
    fileprivate lazy var pictureView: HMComposePictureView =
    {
        let picView = HMComposePictureView()
        picView.backgroundColor = UIColor.white
        
        return picView
    }()
    
    //设置表情键盘
    fileprivate lazy var emoticonView: HMEmoticonKeyboardView =
    {
       let emoticon = HMEmoticonKeyboardView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: ScreenWidth, height: 216)))
        
        return emoticon
    }()
    
    //MARK: --设置界面
    func setupUI()
    {
        //注册通知,监听键盘的frame的变化
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChanged(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //注册通知,监听表情键盘的输入
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonClick(noti: )), name: NSNotification.Name(ClickEmotionButtonNotificationName), object: nil)
        //注册通知,监听删除按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(deleteButtonAction), name: NSNotification.Name(ClickDeleteButtonNotificationName), object: nil)
        
        view.addSubview(composeTextView)
        view.addSubview(toolBarStackView)
        composeTextView.addSubview(pictureView)
        composeTextView.backgroundColor = UIColor.white
        
        composeTextView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(view)
            make.bottom.equalTo(toolBarStackView.snp.top)
        }
        
        toolBarStackView.snp.makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(35)
        }
    
        pictureView.snp.makeConstraints { (make) in
            make.top.equalTo(composeTextView).offset(100)
            make.centerX.equalTo(composeTextView)
            make.width.equalTo(composeTextView).offset(-20)
            make.height.equalTo(composeTextView.snp.width).offset(-20)
        }
        
        toolBarStackView.toolBarCallBack = { (type: HMComposeToolBarButtonType) -> () in
            
            switch type {
            case .picture:
                print("照片")
                self.pictureButtonAction()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self.emoticonButtonAction()
            case .add:
                print("加号")
            }
        }
        
        pictureView.pictureViewCallBack = {
            //开启照片选择器
            self.pictureButtonAction()
        }
    }
    
    //MARK: --删除按钮的监听方法
    @objc private func deleteButtonAction()
    {
        composeTextView.deleteBackward()
    }
    
    //MARK: --发送按钮的监听方法
    @objc private func sendButtonAction()
    {
        let accessToken = HMUserAccountViewModel.sharedUserAccount.accessToken!
        
//        let statusText = composeTextView.text!
        let statusText = composeTextView.emoticonText
        
//        //  在指定范围遍历textView的富文本获取对应的表情描述和普通的字符串，然后进行拼接发送给后台
//        var result = ""
//    
//        composeTextView.attributedText.enumerateAttributes(in: NSMakeRange(0, composeTextView.attributedText.length), options: []) { (info, range, _) in
//            //  info: 富文本信息 -->是一个字典
//            //  range: 富文本对应的范围
//            //  nsrange转字符串
//            print(NSStringFromRange(range))
//
//            if let attachment = info["NSAttachment"] as? HMEmoticonTextAttachment
//            {
//                //  图片表情， 表情富文本
//                let chs = attachment.emoticon!.chs!
//                result += chs
//            }
//            else
//            {
//                //普通字符串富文本
//                let subAttributeStr = composeTextView.attributedText.attributedSubstring(from: range)
//                //将富文本转为字符串
//                let text = subAttributeStr.string
//                result += text
//            }
//        }
        
        //发送等待提示
        SVProgressHUD.show()
        
        if pictureView.pictureArray.count > 0
        {
            let image = pictureView.pictureArray.first!
            
            NetworkTools.shareTools.sendMessage(access_token: accessToken, status: statusText, pic: image, callBack: { (response, error) in
                
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败!")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功!")
            })
        }
        else
        {
            NetworkTools.shareTools.sendMessage(access_token: accessToken, status: statusText) { (response, error) in
                
                if error != nil
                {
                    SVProgressHUD.showError(withStatus: "发送失败!")
                    
                    return
                }
                else
                {
                    SVProgressHUD.showSuccess(withStatus: "发送成功!")
                }
            }
        }
        
    }
    
    //MARK: --监听键盘frame变化的方法
    @objc private func keyBoardFrameChanged(noti: NSNotification)
    {
//        print(noti)
        let keyBoardRect = noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! CGRect
        print(keyBoardRect)
        
        //更改toolBarStackView的约束
        toolBarStackView.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyBoardRect.origin.y - ScreenHeight)
        }
        
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK: --表情按钮的点击方法
    @objc private func emoticonButtonClick(noti: NSNotification)
    {
        let emoticon = noti.object as! HMEmoticon
        
        composeTextView.insertEmoticon(emoticon: emoticon)
        
        HMEmoticonTools.sharedTools.saveRecentEmoticon(emoticon: emoticon) { 
            emoticonView.reloadRecentData()
        }
//        if emoticon.type == "0"
//        {
//            //图片表情
//            let lastEmoticonAttributeText = NSMutableAttributedString(attributedString: composeTextView.attributedText)
//            // 1.创建UIImage对象
//            let image = UIImage(named: emoticon.path!, in: EmoticonButton, compatibleWith: nil)
//            // 2.创建文本附件(NSTextAttachment)
//            let textAttachment = NSTextAttachment()
//            //获取文字高度
//            let lineHeight = composeTextView.font!.lineHeight
//            //更改富文本的bounds,使文字能够和富文本对齐
//            textAttachment.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
//            // 3.设置文本附件对应的图片对象
//            textAttachment.image = image
//            // 4.根据文本附件创建富文本
//            let emoticonAttributeText = NSAttributedString(attachment: textAttachment)
////            lastEmoticonAttributeText.append(emoticonAttributeText)
//            // 5.设置富文本
//            
//            //设置光标选中范围
//            var range = composeTextView.selectedRange
//            //替换选中范围-> 富文本
//            lastEmoticonAttributeText.replaceCharacters(in: range, with: emoticonAttributeText)
//            //统一设置富文本的文字大小
//            lastEmoticonAttributeText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 15)], range: NSMakeRange(0, lastEmoticonAttributeText.length))
//            
//            //设置光标的位置
//            range.location += 1
//            range.length = 0
//            composeTextView.selectedRange = range
//            
//            composeTextView.attributedText = lastEmoticonAttributeText
//        }
//        else
//        {
//            //emoji表情
//            let emoji = (emoticon.code! as NSString).emoji()
//            //  设置textView内容, 插入到光标后面
//            composeTextView.insertText(emoji!)
//        }
    }
    
    //MARK: --设置navigationBar
    func setupNavUI()
    {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        //初始值不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    //MARK: --取消 leftBarButtonItem
    @objc private func cancelAction()
    {
        //失去第一响应者身份
        composeTextView.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
}

//MARK: --点击toolBar按钮后,回调的方法
extension HMComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
    //点击表情按钮的方法
    func emoticonButtonAction()
    {
        //  设置键盘顶部功能条
        //        textView.inputAccessoryView
        
        if composeTextView.inputView == nil
        {
            composeTextView.inputView = emoticonView
            
            toolBarStackView.switchButtonIcon(isEmoticonButton: true)
        }
        else
        {
            composeTextView.inputView = nil
            
            toolBarStackView.switchButtonIcon(isEmoticonButton: false)
        }
        
        composeTextView.becomeFirstResponder()
        composeTextView.reloadInputViews()
    }
    
    //点击照片按钮的方法
    func pictureButtonAction()
    {
        let picker = UIImagePickerController()
        picker.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.camera)
        {
            //真机
            picker.sourceType = .camera
        }
        else
        {
            //模拟器, 设置图库
            picker.sourceType = .photoLibrary
        }
        
        self.present(picker, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//        print(info)
        //获取选中的图片
        let selectedImage = info["UIImagePickerControllerOriginalImage"] as! UIImage
        
        let scaledImage = scaleImage(image: selectedImage, scaleWidth: 200)

        pictureView.showSelectedPicture(image: scaledImage)
        
        dismiss(animated: true, completion: nil)
    }
    
    func scaleImage(image: UIImage, scaleWidth: CGFloat) -> UIImage
    {
        //压缩后的高度
        let scaleHeight = scaleWidth * image.size.height / image.size.width
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        
        //开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        
        let range = CGRect(origin: CGPoint.zero, size: scaleSize)
        image.draw(in: range)
        
        //  在图片上下文中获取压缩后的图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图片上下文
        UIGraphicsEndImageContext()
        
        return currentImage!
    }
}

//MARK: --UITextView 的代理方法
extension HMComposeViewController: UITextViewDelegate
{
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = composeTextView.hasText
    }
}
